/**
 * 计算甘特图的总时长（小时）
 * 
 * @description 动态计算总时长 (Top Scale) - 自动扩展以包含所有数据
 * @param ganttData - 甘特图数据对象
 * @param selectedTopScale - 顶层刻度选择
 * @param startDateTime - 开始时间
 * @param minMaxTime - 最小/最大时间范围
 * @returns 总时长（小时数，可能是小数）
 */

import { computed, ComputedRef, Ref } from 'vue'
import { GanttData, TimeRange } from './types'

export function useTotalHours(
  ganttData: GanttData,
  selectedTopScale: Ref<string>,
  startDateTime: ComputedRef<Date>,
  minMaxTime: ComputedRef<TimeRange | null>
): ComputedRef<number> {
  return computed(() => {
    const map: Record<string, number> = {
      '1天': 24, '2天': 48, '3天': 72, '1周': 168
    }
    const baseHours = map[selectedTopScale.value] || 24
    
    // 计算基于 K时刻的默认结束时间
    const timeStr = ganttData.simulation.currentTime
    let kTimeMs = Date.now()
    if (timeStr) {
      const d = new Date(timeStr.replace(/-/g, '/'))
      if (!isNaN(d.getTime())) kTimeMs = d.getTime()
    }
    
    const halfRangeMs = (baseHours / 2) * 60 * 60 * 1000
    let endMs = kTimeMs + halfRangeMs

    // 自动扩展：如果数据更晚，则延伸结束时间 (留1小时余量)
    if (minMaxTime.value && minMaxTime.value.max > endMs) {
      endMs = minMaxTime.value.max + (1 * 60 * 60 * 1000)
    }

    const startMs = startDateTime.value.getTime()
    const durationMs = endMs - startMs

    // 转换回小时 (可能是小数)
    return durationMs / (1000 * 60 * 60)
  })
}
